package com.sh.d1.gameserver.cmdhandler;

import com.sh.d1.gameserver.model.MoveState;
import com.sh.d1.gameserver.model.User;
import com.sh.d1.gameserver.model.UserManager;
import com.sh.d1.gameserver.msg.GameMsgProtocol;

/**
 * 还有谁在场指令处理器
 */
public class WhoElseIsHereCmdHandler implements ICmdHandler<GameMsgProtocol.WhoElseIsHereCmd> {
    @Override
    public void handle(MyCmdHandlerContext ctx, GameMsgProtocol.WhoElseIsHereCmd cmd) {
        if (null == ctx ||
            null == cmd) {
            return;
        }

        GameMsgProtocol.WhoElseIsHereResult.Builder
            resultBuilder = GameMsgProtocol.WhoElseIsHereResult.newBuilder();

        for (User currUser : UserManager.listUser()) {
            if (null == currUser) {
                continue;
            }

            // 构建用户信息
            GameMsgProtocol.WhoElseIsHereResult.UserInfo.Builder
                userInfoBuilder = GameMsgProtocol.WhoElseIsHereResult.UserInfo.newBuilder();
            userInfoBuilder.setUserId(currUser.userId);
            userInfoBuilder.setUserName(currUser.userName);
            userInfoBuilder.setHeroAvatar(currUser.heroAvatar);

            // 构建移动状态
            MoveState mvState = currUser.moveState;
            GameMsgProtocol.WhoElseIsHereResult.UserInfo.MoveState.Builder
                mvStateBuilder = GameMsgProtocol.WhoElseIsHereResult.UserInfo.MoveState.newBuilder();
            mvStateBuilder.setFromPosX(mvState.fromPosX);
            mvStateBuilder.setFromPosY(mvState.fromPosY);
            mvStateBuilder.setToPosX(mvState.toPosX);
            mvStateBuilder.setToPosY(mvState.toPosY);
            mvStateBuilder.setStartTime(mvState.startTime);
            // 设置移动状态
            userInfoBuilder.setMoveState(mvStateBuilder);

            // 添加用户信息到结果
            resultBuilder.addUserInfo(userInfoBuilder);
        }

        GameMsgProtocol.WhoElseIsHereResult newResult = resultBuilder.build();
        ctx.writeAndFlush(newResult);
        // XXX 注意: 这里是谁问就给谁发, 而不是群发
    }
}
